package com.cheng.reggie.service.impl;

import com.cheng.reggie.entity.User;
import com.cheng.reggie.exception.BusinessException;
import com.cheng.reggie.mapper.UserMapper;
import com.cheng.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 用户登录方法
     *
     * @param phone       手机号
     * @param userCode    用户输入验证码
     * @param sessionCode 后端生成验证码
     * @return User 返回登录的用户对象
     */
    @Override
    public User longin(String phone, String userCode, String sessionCode) {
        //1.传过来手机号,用户输入
        //2.校验验证码是否正确,如果不正确返回"验证码错误"
        if(!userCode.equals(sessionCode)){
            throw new BusinessException("验证码错误");
        }
        //3.根据手机号查找用户对象,判断是否禁用,如果找到并且没有禁用返回
        User loginUser = userMapper.findByPhone(phone);
        if (loginUser != null) {
            if (loginUser.getStatus() == 1){
                throw new BusinessException("您的手机号已经被禁用");
            }
        }else {
            //4如果找不到,完善用户数据(设置状态为1正常)并添加用户到数据库
            loginUser = new User();
            loginUser.setStatus(0);
            loginUser.setPhone(phone);
            userMapper.save(loginUser);
        }
        //返回登录用户对象
        return loginUser;
    }
}
